 package com.wisdom;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.ViewSwitcher;

import com.wisdom.adapter.NewsDetailAdapter;
import com.wisdom.http.HttpNewsService;
import com.wisdom.http.HttpRequestService;
import com.wisdom.http.HttpRequestUrl;
import com.wisdom.utils.ActivityUtil;
import com.wisdom.utils.StringUtils;
import com.wisdom.view.MyListView;
import com.wisdom.view.MyListView.OnRefreshListener;
import com.wisdom.vo.Comments;
import com.wisdom.vo.News;
import com.wisdom.vo.Users;


public class NewsContentActivity extends Activity 
{
	//"特大号字体","大号字体","中号字体","小号字体"
	public static final String TEXT_SIZE_VIRY = "特大号字体";
	public static final String TEXT_SIZE_BIG = "大号字体";
	public static final String TEXT_SIZE_CENTER="中号字体";
	public static final String TEXT_SIZE_LITTLE = "小号字体";
	private ImageButton btn_back;
	private String content_url;

	private ViewSwitcher viewSwitcher;
	private HttpNewsService service;
	private View view;
	private Map<String,String> params;
	private TextView tv_news_detials_title,tv_news_detail_source,tv_news_details_content;
	private ImageView iv_news_detais_pic;
	private MyListView listView;
	private NewsDetailAdapter adapter;
	private Button button;
	private News news;
	private static final int COUNT = 5;
	private TextView tv_count;
	private EditText et_writer_comment;
	private LinearLayout ll_writer,ll_witer_comments_menu;
	private ToggleButton tb_select_witer;
	private int count;
	private float textSize;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_newscontent);
		initViews();
	}

	private void initViews() 
	{
		btn_back = (ImageButton) findViewById(R.id.btn_newscontent_back);
		btn_back.setOnClickListener(listener);

		viewSwitcher = (ViewSwitcher) findViewById(R.id.viewSwitcher);
		tv_count = (TextView) findViewById(R.id.tv_detail_count);
		et_writer_comment = (EditText) findViewById(R.id.et_write_comments);
		tb_select_witer = (ToggleButton) findViewById(R.id.tb_select_witer);
		tb_select_witer.setOnCheckedChangeListener(changeListener);
		ll_witer_comments_menu = (LinearLayout) findViewById(R.id.ll_witer_comments_menu);
		ll_writer = (LinearLayout) findViewById(R.id.ll_writer);
		content_url = getIntent().getStringExtra("content_url");
		count = Integer.parseInt(getIntent().getStringExtra("count"));
		tv_count.setText(count+"跟帖");
		// 向ViewSwitcher中添加两个View，用来切换
		view = getLayoutInflater().inflate(R.layout.layout_news_deatils,null);
		listView = new MyListView(this);
		
		int[] colors = {0, 0xFF999999, 0};
		listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
		listView.setDividerHeight(1);


		
		listView.addHeaderView(view);
		
		button = new Button(this);
		button.setText("查看更多的评论");
		button.setHint("6");
		button.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				nextPage();
			}
		});
		listView.addFooterView(button);
		listView.setonRefreshListener(refreshListener);
		listView.setOnItemClickListener(listenerItem);
		viewSwitcher.addView(listView);
		viewSwitcher.addView(getLayoutInflater().inflate(R.layout.layout_progress_page, null));
		viewSwitcher.showNext();
		service = new HttpNewsService();
		loadData();
		
	}
	
	private OnRefreshListener refreshListener = new OnRefreshListener() 
	{
		
		@Override
		public void onRefresh() 
		{
			new AsyncTask<Map<String,String>, Integer, List<News>>()
			{

				@Override
				protected List<News> doInBackground(Map<String, String>... params) 
				{
					try 
					{
						Thread.sleep(1000);
					} catch (Exception e) {
						e.printStackTrace();
					}
					data();
					return null;
				}
				@Override
				protected void onPostExecute(List<News> result) 
				{
					button.setHint(21+"");
					comments();
					listView.onRefreshComplete();
				}
				
			}.execute();
		}
	};

	private OnClickListener listener = new OnClickListener() 
	{

		@Override
		public void onClick(View v) 
		{
			NewsContentActivity.this.setResult(RESULT_OK);
			NewsContentActivity.this.finish();
		}
	};
	
	private void loadData()
	{
		data();
		comments();
		viewSwitcher.showPrevious();
	}
	
	private void comments()
	{
		if(news!=null)
		{
			this.tv_news_detail_source = (TextView) view.findViewById(R.id.tv_news_detail_source);
		    this.tv_news_details_content = (TextView) view.findViewById(R.id.tv_news_details_content);
		    this.tv_news_detials_title = (TextView) view.findViewById(R.id.tv_news_detials_title);
		    this.iv_news_detais_pic = (ImageView) view.findViewById(R.id.iv_news_detais_pic);
		    this.tv_news_detail_source.setText(news.getNewsSource()+" "+news.getNewsData());
		    this.tv_news_details_content.setText(news.getNewsContent());
		    this.tv_news_detials_title.setText(news.getNewsTitle());
		    this.tv_news_detials_title.setHint(news.getNewsId()+"");
		    textSize = this.tv_news_details_content.getTextSize();
		    if(news.getPhotos().size()>0)
		    {
				String photoUrl = this.getResources().getString(R.string.android_url);
				String photoName = news.getPhotos().get(0).getNewsFilmResourceUrl();
				File file = new File(photoUrl,photoName.split("/")[1]);
				//从后台读取照片
				if(!file.exists())
				{
					new HttpRequestService().putPhoto(photoName, file, this);
				}
				this.iv_news_detais_pic.setImageURI(Uri.fromFile(file));
			}	
		    adapter = new NewsDetailAdapter(news.getComments(), this);
		    listView.setAdapter(adapter);
		}
	}
	private void data()
	{
		params = new HashMap<String, String>();
		params.put("news.newsId", content_url);
		String data = service.requestByPost(HttpRequestUrl.url(HttpRequestUrl.NEWS_LOAD), params);
		news = service.loadNews(data);
	}
	
	private void nextPage()
	{
		if(news.getComments().size()%5!=0)
		{
			ActivityUtil.toast(this, "评论已加载完毕");
		}
		else
		{
			int startIndex = Integer.parseInt(button.getHint().toString());
			int endIndex = startIndex+COUNT;
			params = new HashMap<String, String>();
			params.put("comments.startIndex", startIndex+"");
			params.put("comments.endIndex", endIndex+"");
			String data = service.requestByPost(HttpRequestUrl.url(HttpRequestUrl.COMMENTS_SELECT), params);
			List<Comments> list = service.parseComments(data, news.getComments());
			
			if(list==null)
			{
				ActivityUtil.toast(this, "没有评论加载了");
				return;
			}
			
			news.setComments(list);
			adapter.notifyDataSetChanged();
			button.setHint(endIndex+"");	
		}
	}
	//
	private OnCheckedChangeListener changeListener = new OnCheckedChangeListener() 
	{
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
		{
			if(isChecked)
			{
				ll_witer_comments_menu.setVisibility(View.VISIBLE);
			}
			else
			{
				ll_witer_comments_menu.setVisibility(View.INVISIBLE);
			}
			
		}
	};
	public void menuSelect(View view)
	{
		
		if(news==null)
		{
			ActivityUtil.toast(this, "文章未加载完,操作无效");
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch(view.getId())
		{
		case R.id.ll_collect:
			//收藏
			if(Users.user == null )
			{
				Intent intent = new Intent(this, LoginActivity.class);
				this.startActivityForResult(intent, 1);
				return;
			}
			params = new HashMap<String, String>();
			params.put("collect.newsCollectUserId", Users.user.getUserId()+"");
			params.put("collect.newsCollectNewsId", news.getNewsId()+"");
			String data = service.requestByPost(HttpRequestUrl.url(HttpRequestUrl.USER_COLLECT), params);
			
			if(Boolean.parseBoolean(data))
			{
				ActivityUtil.toast(this, "收藏成功");
			}
			else
			{
				ActivityUtil.toast(this, "收藏失败");
			}
			
			break;
		case R.id.ll_writer_comment:
			ll_writer.setVisibility(View.VISIBLE);
			ll_witer_comments_menu.setVisibility(View.INVISIBLE);
			break;
		case R.id.ll_aa:
			final String[] items = new String[]{TEXT_SIZE_VIRY,TEXT_SIZE_BIG,TEXT_SIZE_CENTER,TEXT_SIZE_LITTLE};
			builder.setTitle("正文字体");
			builder.setIcon(null);
			builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() 
			{
				public void onClick(DialogInterface dialog, int which) 
				{
					if(items[which].equals(TEXT_SIZE_VIRY))
					{
						textSize = 26.0f;
					}
					else if(items[which].equals(TEXT_SIZE_BIG))
					{
						textSize = 20.0f;
					}
					else if(items[which].equals(TEXT_SIZE_CENTER))
					{
						textSize = 14.0f;
					}
					else if(items[which].equals(TEXT_SIZE_LITTLE))
					{
						textSize = 8.0f;
					}
				}
			});
    		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() 
    		{
				public void onClick(DialogInterface dialog, int which) 
				{
					tv_news_details_content.setTextSize(textSize);
					
				}
			});
    		builder.show();
			break;
		}
	}
	//发送帖子
	public void send(View view)
	{
		if(Users.user == null )
		{
			Intent intent = new Intent(this, LoginActivity.class);
			this.startActivityForResult(intent, 1);
			return;
		}
		
		String content = et_writer_comment.getText().toString();
		
		if(StringUtils.isBlank(content))
		{
			ActivityUtil.toast(this, "请输入要发表的内容");
			return;
		}
		
		params = new HashMap<String, String>();
		params.put("comments.commentsNewsId", news.getNewsId()+"");
		params.put("comments.commentsContent", content);
		params.put("comments.commentsUserId", Users.user.getUserId()+"");
		String data = service.requestByPost(HttpRequestUrl.url(HttpRequestUrl.COMMENTS_ADD), params);
		if(Boolean.parseBoolean(data))
		{
			params = new HashMap<String, String>();
			params.put("comments.startIndex", 1+"");
			params.put("comments.endIndex", 6+"");
			params.put("comments.commentsNewsId", news.getNewsId()+"");
			data = service.requestByPost(HttpRequestUrl.url(HttpRequestUrl.COMMENTS_SELECT), params);
			news.setComments(service.parseComments(data, new ArrayList<Comments>()));
			listView.setAdapter(new NewsDetailAdapter(news.getComments(),this));
			button.setHint(6+"");
			count+=1;
			tv_count.setText(count+"跟帖");
			et_writer_comment.setText(null);
			ActivityUtil.toast(this, "发表成功");
		}
		else
		{
			ActivityUtil.toast(this, "发表失败");
		}
	}
	private OnItemClickListener listenerItem = new OnItemClickListener() 
	{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
		{
			ll_writer.setVisibility(View.INVISIBLE);
			ll_witer_comments_menu.setVisibility(View.INVISIBLE);
		}
	};
}
